package com.projectdemo.springbootdemo1.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests(authorize -> authorize
                .antMatchers("/public/**").permitAll()
                .antMatchers("/druid/**").permitAll()// druid无需认证
                .antMatchers("/admin/**").hasRole("ADMIN") // 只有管理员可访问
                                .anyRequest().authenticated() // 其他路径需要认证)
                ).formLogin(form -> form
                        .loginPage("/login") // 自定义登录页
                        .permitAll() // 登录页允许所有用户访问
                )
                .logout(logout -> logout
                        .logoutUrl("/logout") // 自定义登出路径
                        .logoutSuccessUrl("/login?logout") // 登出后跳转
                );
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(); // 密码加密器
    }
}
